package projet.ejb;

import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import projet.entity.Fondateur;
import projet.entity.Investisseur;
import projet.entity.Startup;

@Stateless
public class StartupFacadeEJB implements StartupFacade {

	@PersistenceContext(unitName = "SampleUnit")
	protected EntityManager entityMgr;

	public Startup add(Startup s) {
		entityMgr.persist(s);
		return s;	
	}

	public Startup findByName(String nom){
		Query query = entityMgr.createQuery("SELECT s FROM Startup as s WHERE s.nom=:n ");
		query.setParameter("n", nom);
		Startup s =   (Startup) query.getSingleResult();
		return s;
	}

	@SuppressWarnings("unchecked")
	public Collection<Startup> findAll() {
		return entityMgr.createQuery("SELECT s FROM Startup as s").getResultList();
	}

	public void deleteAll() {
		Collection<Startup> l_startup = findAll();
		for(Startup s : l_startup){
			entityMgr.remove(s);
		}
	}

	public Startup update(Startup s){
		return entityMgr.merge(s);
	}	

	@Override
	public Startup charger_Lcours(int id) {
		Query query = entityMgr.createQuery("SELECT s FROM Startup s JOIN FETCH s.l_cours WHERE s.id_startup=:n ");
		query.setParameter("n", id);
		Startup s =   (Startup) query.getSingleResult();
		return s;
	}

	@Override
	public Startup charger_LParticipation(int id) {
		Query query = entityMgr.createQuery("SELECT s FROM Startup s JOIN FETCH s.l_participation WHERE s.id_startup=:n ");
		query.setParameter("n", id);
		Startup s =   (Startup) query.getSingleResult();
		return s;		
	}

	@Override
	public Startup charger_Llevee(int id) {
		Query query = entityMgr.createQuery("SELECT s FROM Startup s JOIN FETCH s.l_levee WHERE s.id_startup=:n ");
		query.setParameter("n", id);
		Startup s =   (Startup) query.getSingleResult();
		return s;
	}

	@Override
	public Startup charger_Liste_ALL(int id) {
		Query query = entityMgr.createQuery("SELECT s FROM Startup s JOIN FETCH s.l_cours " +
										"JOIN FETCH s.l_participation" +
									" JOIN FETCH s.l_levee " +
									"WHERE s.id_startup=:n ");
		query.setParameter("n", id);
		Startup s =   (Startup) query.getSingleResult();
		return s;
	}

	@Override
	public Startup findById(int id) {
		Query query = entityMgr.createQuery("SELECT s FROM Startup s WHERE s.id_startup=:n ");
		query.setParameter("n", id);
		Startup s =  (Startup) query.getSingleResult();
		return s;
	}

	@Override
	public void delete(int id) {
		Startup s = entityMgr.find(Startup.class,id);
		entityMgr.remove(s);
	}

}
